import NetService from './net.service'
import { ref, reactive } from 'vue'
import { Service, injectable, mutex } from './service'

@injectable
export default class TurnoutsSectionService extends Service {
  public turnoutsSection = ref([] as Any[])

  public addData = reactive({
    id: '',
    section: ''
  })

  private netService = new NetService()

  @mutex
  async load () {
    // 加载全部 区段 数据
    // 判断是否全部加载 如果已经加载 忽略
    const res = await this.netService.get('/turnout/section/list')
    if (res?.success) {
      res?.data.forEach((item: { direction: string | number; id: { toString: (arg0: number) => string }; section: { toString: (arg0: number) => string }; turnout: { toString: (arg0: number) => string } }, index: number) => {
        item.direction = item.direction === 0 ? '左线' : '右线'
        item.id = item.id.toString(16).replace('"', '').replace('"', '').toUpperCase()
        item.section = item.section.toString(16).replace('"', '').replace('"', '').toUpperCase()
        item.turnout = item.turnout.toString(16).replace('"', '').replace('"', '').toUpperCase()
      })
      this.turnoutsSection.value = res?.data
    }
  }

  async add (params: {
    id:string,
    section:string,
    turnout:string,
    value:string
  }) {
    const res = await this.netService.post('/turnout/section/insert', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.turnout = parseInt(params.turnout).toString(16).toUpperCase()
      params.section = parseInt(params.section).toString(16).toUpperCase()
      this.turnoutsSection.value.push(params)
    }
    return res
  }

  async change (params: {
    id:string,
    section:string,
    turnout:string,
    value:string
  }) {
    const res = await this.netService.post('/turnout/section/update', params)
    if (res?.success) {
      params.id = parseInt(params.id).toString(16).toUpperCase()
      params.section = parseInt(params.section).toString(16).toUpperCase()
      params.turnout = parseInt(params.turnout).toString(16).toUpperCase()
      const delIndex = this.turnoutsSection.value.findIndex((e, index) => {
        return e.id === params.id
      })
      this.turnoutsSection.value.splice(delIndex, 1, params)
    }
    return res
  }

  async del (params: { id: string }) {
    const res = await this.netService.post('/turnout/section/delete', params, 'posturl')
    if (res?.success) {
      const delIndex = this.turnoutsSection.value.findIndex((e, index) => {
        return e.id === parseInt(params.id).toString(16).toUpperCase()
      })
      this.turnoutsSection.value.splice(delIndex, 1)
    }
    return res
  }
}
